package com.dcbeida.activity.salsesdedail;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.dcbeida.MyApplication;
import com.dcbeida.R;
import com.dcbeida.activity.BaseActivity;
import com.dcbeida.activity.CommonListActivity;
import com.dcbeida.activity.hospital.HospitalActivity;
import com.dcbeida.adapter.StoreAdapter;
import com.dcbeida.bean.CardEnum;
import com.dcbeida.bean.HospitalBean;
import com.dcbeida.bean.Image;
import com.dcbeida.bean.Sales;
import com.dcbeida.utils.Constants;
import com.dcbeida.utils.GetPhotoFromAlbum;
import com.dcbeida.utils.GifSizeFilter;
import com.dcbeida.utils.PutAliyObject;
import com.dcbeida.utils.Utils;
import com.dcbeida.utils.permission.AndPermission;
import com.dcbeida.utils.permission.PermissionListener;
import com.dcbeida.utils.permission.Rationale;
import com.dcbeida.utils.permission.RationaleListener;
import com.dcbeida.widget.DialogToast;
import com.dcbeida.widget.PhotoViewShow;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.SelectionCreator;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import anet.channel.util.StringUtils;
import butterknife.Bind;
import butterknife.OnClick;

import static com.dcbeida.utils.Constants.PERMISSION_CAMERA;
import static com.dcbeida.utils.Constants.PERMISSION_WRITE_EXTERNAL_STORAGE;
import static com.dcbeida.utils.Constants.REQUEST_CODE_CHOOSE;
import static com.dcbeida.utils.Constants.REQUEST_CODE_CHOOSE_CF;

/**
 * 编辑销售详情
 * Created by swt on 2017/9/29.
 */

public class SalsesDetailUpdateActivity extends BaseActivity implements SalsesDetailUpdateContract.View {


    @Bind(R.id.img_back)
    ImageView imgBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.rel_title1)
    RelativeLayout relTitle1;
    @Bind(R.id.tv_hzmz)
    TextView tvHzmz;
    @Bind(R.id.tv_hzsjh)
    TextView tvHzsjh;
    @Bind(R.id.tv_hzsfzh)
    TextView tvHzsfzh;
    @Bind(R.id.tv_yymc)
    TextView tvYymc;
    @Bind(R.id.ll_yymc)
    LinearLayout llYymc;
    @Bind(R.id.tv_zzys)
    EditText tvZzys;
    @Bind(R.id.tv_id_card_type)
    TextView tv_id_card_type;
    @Bind(R.id.tv_tel_type)
    TextView tv_tel_type;

    @Bind(R.id.tv_je)
    EditText tvJe;
    @Bind(R.id.tv_hj)
    TextView tvHj;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    @Bind(R.id.recyclerview2)
    RecyclerView recyclerview2;

    @Bind(R.id.scrollView)
    ScrollView scrollView;
    private SalsesDetailUpdatePresenter mPresent;
    private Sales.ListBean salesBean;
    private StoreAdapter storeAdapter;
    private StoreAdapter storeAdapter2;
    private static final String[] requestPermissions = {
            PERMISSION_CAMERA,
            PERMISSION_WRITE_EXTERNAL_STORAGE
    };
    private List<String> obtainPathResult;//本地图片地址
    private List<String> obtainPathCfResult;//本地图片地址

    private ArrayList<String> imgUrl;//服务器图片地址

    private ArrayList<String>cfImgUrl;//服务器图片地址
    private ProgressDialog dialog;
    private Handler iHandler;
    private String localUrl;//选取的本地图片url
    private HospitalBean hospitalBean;
    private int hospitalid;
    private String doctorid = "";

    private int telType =0;

    private boolean isShow= false;
    private int currentClickType=REQUEST_CODE_CHOOSE;

    @Override
    protected int getLayoutResId() {
        return R.layout.salses_detail_update;
    }

    @Override
    public void setData() {
        super.setData();
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            salesBean = (Sales.ListBean) bundle.getSerializable("Sales.ListBean");
            hospitalid = Integer.valueOf(salesBean.getHospitalid());
        }
        obtainPathResult = new ArrayList<String>();
        obtainPathCfResult= new ArrayList<String>();
        imgUrl = new ArrayList<String>();
        cfImgUrl= new ArrayList<String>();

        imgBack.setVisibility(View.VISIBLE);
        tvTitle.setText(R.string.mdxs);
        tvRight.setText(R.string.bc);
        tvHzmz.setText(salesBean.getTruename());
        tvHzsjh.setText(salesBean.getPhonenum());
        if(salesBean.getPhonenum() != null && salesBean.getPhonenum().contains("-")){
            telType =1;
            tv_tel_type.setText("固定电话");
        }else{
            tv_tel_type.setText("手机号");
        }



        tv_id_card_type.setText(CardEnum.getCardName(salesBean.getCardtype()));


        tvHzsfzh.setText(salesBean.getIdcardnum());
        tvYymc.setText(salesBean.getHospitalname());
        tvZzys.setText(salesBean.getDoctorname());
        tvJe.setText(salesBean.getAmount());
        tvHj.setText(salesBean.getQuantity());

        //图片地址
        if (!TextUtils.isEmpty(salesBean.getInvoiceimgurl())) {
            if (salesBean.getInvoiceimgurl().indexOf(",") != -1) {
                String[] imgUrlArr = salesBean.getInvoiceimgurl().split(",");
                for (int i = 0; i < imgUrlArr.length; i++) {
                    imgUrl.add(imgUrlArr[i]);
                }
            } else {
                imgUrl.add(salesBean.getInvoiceimgurl());
            }
        }
        obtainPathResult.addAll(imgUrl);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerview.setLayoutManager(layoutManager);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        recyclerview.setHasFixedSize(true);
        storeAdapter = new StoreAdapter(mContext);
        storeAdapter.setDefaultDrawable(R.drawable.shangchuanfap);
        recyclerview.setAdapter(storeAdapter);
        storeAdapter.setData(imgUrl);

        storeAdapter.setOnItemClickListener(new StoreAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == storeAdapter.mUris.size()) {
                    currentClickType = REQUEST_CODE_CHOOSE;
                    //权限申请
                    AndPermission.with(mContext)
                            .requestCode(100)
                            .permission(requestPermissions)
                            .rationale(rationaleListener)
                            .send();
                } else {
                    //传递当前点击的图片的位置、图片路径集合
                    Bundle bundle = new Bundle();
                    bundle.putInt("position", position);
                    bundle.putStringArrayList("mImages", imgUrl);
                    showActivity(PhotoViewShow.class, bundle);
                }
            }

        });

        storeAdapter.setOnItemDelClickListener(new StoreAdapter.OnRecyclerViewItemDelClickListener() {
            @Override
            public void onItemDelClick(View view, int position) {
                obtainPathResult.remove(position);
                imgUrl.remove(position);
                storeAdapter.setData(imgUrl);
            }
        });




        if (!TextUtils.isEmpty(salesBean.getRecipepicsurl())) {
            if (salesBean.getRecipepicsurl().indexOf(",") != -1) {
                String[] imgUrlArr = salesBean.getRecipepicsurl().split(",");
                for (int i = 0; i < imgUrlArr.length; i++) {
                    cfImgUrl.add(imgUrlArr[i]);
                }
            } else {
                cfImgUrl.add(salesBean.getRecipepicsurl());
            }
        }
        obtainPathCfResult.addAll(cfImgUrl);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(mContext);
        layoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerview2.setLayoutManager(layoutManager2);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        recyclerview2.setHasFixedSize(true);
        storeAdapter2 = new StoreAdapter(mContext);
        storeAdapter2.setDefaultDrawable(R.drawable.shangchuanchufang);
        recyclerview2.setAdapter(storeAdapter2);
        storeAdapter2.setData(cfImgUrl);

        storeAdapter2.setOnItemClickListener(new StoreAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == storeAdapter2.mUris.size()) {
                    currentClickType = REQUEST_CODE_CHOOSE_CF;
                    //权限申请
                    AndPermission.with(mContext)
                            .requestCode(100)
                            .permission(requestPermissions)
                            .rationale(rationaleListener)
                            .send();
                } else {
                    //传递当前点击的图片的位置、图片路径集合
                    Bundle bundle = new Bundle();
                    bundle.putInt("position", position);
                    bundle.putStringArrayList("mImages", cfImgUrl);
                    showActivity(PhotoViewShow.class, bundle);
                }
            }

        });

        storeAdapter2.setOnItemDelClickListener(new StoreAdapter.OnRecyclerViewItemDelClickListener() {
            @Override
            public void onItemDelClick(View view, int position) {
                obtainPathCfResult.remove(position);
                cfImgUrl.remove(position);
                storeAdapter2.setData(cfImgUrl);
            }
        });




        addMessageHandler();

        scrollView.smoothScrollTo(0, 0);
        mPresent = new SalsesDetailUpdatePresenter(this, this);

        tvJe.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    tvJe.setText("请输入金额");
                    tvJe.setTextColor(getResources().getColor(R.color.c_aaaaaa));
                } else if (s.toString().contains("请输入金额") && !s.toString().equals("请输入金额")) {
                    if (s != null) {
                        String result = s.toString().replace("请输入金额", "");
                        tvJe.setText(result);
                        tvJe.setTextColor(getResources().getColor(R.color.c_0C87EA));
                    }

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
            rationale.resume();
        }
    };

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantPermissions) {
            SelectionCreator result =Matisse.from(mContext)
                    .choose(MimeType.ofAll(), false)
                    .countable(true)
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, "com.dcbeida.utils.GifSizeFilter"))
                    .maxSelectable(Constants.MAX_IMAGE_SIZE - imgUrl.size())
                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                    .thumbnailScale(0.85f)
                    .imageEngine(new GlideEngine());

            if(currentClickType == REQUEST_CODE_CHOOSE){
                result.maxSelectable(Constants.MAX_IMAGE_SIZE - imgUrl.size());
            }else{
                result.maxSelectable(Constants.MAX_IMAGE_SIZE - cfImgUrl.size());
            }
            result.forResult(currentClickType);


        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {

        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    @OnClick({R.id.img_back, R.id.tv_right, R.id.ll_yymc,R.id.ll_tel_type})
    public void onClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.ll_tel_type:
               Bundle  b = new Bundle();
                b.putInt("type", 1);
                showActivityForResult(CommonListActivity.class, b, Constants.RESULT_TEL_TYPE);

                break;
            case R.id.tv_right:
                if(tvHzmz.getText().toString().isEmpty() ){
                    Toast.makeText(this, "请输入患者姓名", Toast.LENGTH_LONG).show();
                    return;
                }

                if (telType == 0 && tvHzsjh.getText().toString().length() !=11) {
                    showTip("请正确填写患者手机号码");
                    return;
                }

                if (telType == 1 && !tvHzsjh.getText().toString().contains("-")) {
                    showTip("请正确填写患者固定电话");
                    return;
                }

                if (tvJe.getText().toString().isEmpty() ||
                        tvJe.getText().toString().contains("请输入金额")) {
                    Toast.makeText(this, "请输入金额", Toast.LENGTH_LONG).show();
                    return;
                }

                isShow = (!tvHzmz.getText().toString().equals(salesBean.getTruename())) ||
                        (!tvHzsjh.getText().toString().equals(salesBean.getPhonenum())) ;

                if(isShow){
                    new AlertDialog.Builder(this).setTitle("保存确认").setMessage("请核对患者身份证是否与实际相符，以避免错误修改他人档案！确认修改请点击确认按钮。")
                            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).setPositiveButton(R.string.confim, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            String invoiceimgurl = "";
                            for (int i = 0; i < imgUrl.size(); i++) {
                                if (imgUrl.size() == i || i == 0) {
                                    invoiceimgurl += imgUrl.get(i);
                                } else {
                                    invoiceimgurl += "," + imgUrl.get(i);
                                }
                            }

                            String recipepicsurl = "";
                            for (int i = 0; i < cfImgUrl.size(); i++) {
                                if (cfImgUrl.size() == i || i == 0) {
                                    recipepicsurl += cfImgUrl.get(i);
                                } else {
                                    recipepicsurl += "," + cfImgUrl.get(i);
                                }
                            }

                            mPresent.sbumit(salesBean.getId(), hospitalid + "", doctorid,
                                    tvZzys.getText().toString().trim(), tvJe.getText().toString(), "0",
                                    invoiceimgurl, recipepicsurl,"",tvHzmz.getText().toString().trim(),
                                    tvHzsjh.getText().toString().trim());
                        }
                    }).show();
                }else{
                    String invoiceimgurl = "";
                    for (int i = 0; i < imgUrl.size(); i++) {
                        if (imgUrl.size() == i || i == 0) {
                            invoiceimgurl += imgUrl.get(i);
                        } else {
                            invoiceimgurl += "," + imgUrl.get(i);
                        }
                    }

                    String recipepicsurl = "";
                    for (int i = 0; i < cfImgUrl.size(); i++) {
                        if (cfImgUrl.size() == i || i == 0) {
                            recipepicsurl += cfImgUrl.get(i);
                        } else {
                            recipepicsurl += "," + cfImgUrl.get(i);
                        }
                    }


                    mPresent.sbumit(salesBean.getId(), hospitalid + "", doctorid,
                            tvZzys.getText().toString().trim(), tvJe.getText().toString(), "0",
                            invoiceimgurl, recipepicsurl,"",tvHzmz.getText().toString().trim(),
                            tvHzsjh.getText().toString().trim());
                }


                break;
            case R.id.ll_yymc:
                showActivityForResult(HospitalActivity.class, bundle, Constants.HOSPITAL_TYPE);
                break;


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {

            obtainPathResult.addAll(Matisse.obtainPathResult(data));

            updateImg(Matisse.obtainPathResult(data));

        }  else if (requestCode == REQUEST_CODE_CHOOSE_CF && resultCode == RESULT_OK) {
            obtainPathCfResult.addAll(Matisse.obtainPathResult(data));
            updateImg(Matisse.obtainPathResult(data));

        }

        else if (requestCode == Constants.HOSPITAL_TYPE && resultCode == RESULT_OK) {//选择医院
            Bundle bundle = data.getExtras();
            if (null != bundle) {
                if (bundle.containsKey("hospitalBean")) {
                    hospitalBean = (HospitalBean) bundle.getSerializable("hospitalBean");
                    tvYymc.setText(hospitalBean.getHospitalname());
                    hospitalid = hospitalBean.getHospitalid();
                }
            }

        }else if(resultCode == RESULT_OK && requestCode == Constants.RESULT_TEL_TYPE){
            String key = data.getStringExtra("key");
            tv_tel_type.setText(key);
            telType = data.getIntExtra("value",0);
        }
    }

    private void updateImg(List<String> obtainPathResult) {
        dialog = new ProgressDialog(mContext, R.style.myDialogTheme);
        dialog.show();
        View layout = View.inflate(mContext, R.layout.progress, null);
        TextView tv_tip = (TextView) layout.findViewById(R.id.tv_tip);
        tv_tip.setText(R.string.zzsc);
        dialog.setContentView(layout);
        Window win = dialog.getWindow();
        win.setGravity(Gravity.CENTER);
        // 弹出对话框时，底部窗体，不变暗。
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = (int) (MyApplication.widthPixels * 0.85);
        win.setAttributes(lp);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    if (null != dialog) {
                        dialog.dismiss();
                        return true;
                    }
                }
                return false;
            }
        });

        GetPhotoFromAlbum.compressImageByQualityList(obtainPathResult, mContext, iHandler);
    }


    /**
     * 处理接收消息
     */
    private void addMessageHandler() {
        iHandler = new Handler() {
            public void handleMessage(Message msg) {
                try {
                    switch (msg.what) {
                        case Constants.UploadSuccess://阿里云上传图片成功
                            Image img = (Image) msg.obj;
                            if(currentClickType == REQUEST_CODE_CHOOSE) {
                                imgUrl.add(img.getImagepath());

                                if (imgUrl.size() == obtainPathResult.size()) {
                                    dialog.dismiss();
                                    storeAdapter.setData(imgUrl);
                                }
                            }else  if(currentClickType == REQUEST_CODE_CHOOSE_CF){
                                cfImgUrl.add(img.getImagepath());
                                if (cfImgUrl.size() == obtainPathCfResult.size()) {
                                    dialog.dismiss();
                                    storeAdapter2.setData(cfImgUrl);
                                }
                            }


                            break;

                        case Constants.UploadFailed://阿里云上传图片失败
                            dialog.dismiss();
                            showTip("上传图片失败");
                            break;
                        case 100://开始阿里云上传
                            localUrl = (String) msg.obj;
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    new PutAliyObject(MyApplication.oss, Constants.imgBucket, Utils.getOKey(), localUrl, iHandler).asyncPutObjectFromLocalFile();
                                }
                            }).start();
                            break;

                        default:

                            break;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("error.Root", e.toString());
                }
                super.handleMessage(msg);
            }
        };
    }


    @Override
    public void setPresenter(SalsesDetailUpdateContract.Present presenter) {

    }

    @Override
    public void showTip(String msg) {
        super.showTip(msg);
    }
}
